/*
 * TMediaCasterConnection.h
 *
 *  Created on: 2016年7月14日
 *      Author: terry
 */

#ifndef TMEDIACASTERCONNECTION_H_
#define TMEDIACASTERCONNECTION_H_

#include "MediaStream.h"
#include "Socket.h"
#include "TThread.h"
#include "TEvent.h"
#include "TCriticalSection.h"
#include "SharedPtr.h"
#include "MediaPacketQueue.h"
#include <json/json.h>
#include "MediaTransport.h"
#include "TByteBuffer.h"

namespace av
{

class TMediaCasterServer;

class TMediaCasterConnection: public MediaSink,
								public comn::Thread,
								public std::enable_shared_from_this< TMediaCasterConnection >
{
public:
	TMediaCasterConnection();
	virtual ~TMediaCasterConnection();

	bool open(comn::Socket& sock, comn::SockAddr& addr, TMediaCasterServer* server);
	void close();
	bool isOpen();

	std::string	getStreamName() const;

	socket_t getSocket() const;

	comn::SockAddr getPeerName() const;

protected:
    virtual void onMediaFormat(const MediaFormat& fmt);

    virtual void onMediaPacket(MediaPacketPtr& pkt);

    virtual void onMediaEvent(int event);

protected:
	virtual int run();
	virtual void doStop();



    bool checkRead(long ms);

    bool handleCommand();

    void handleClose();

    void closeSocket();

    bool sendPacket(MediaPacketPtr& pkt);

protected:
	comn::Socket	m_socket;
	comn::SockAddr	m_addr;
	std::string	m_streamName;
	std::string m_peerID;
	TMediaCasterServer*	m_server;

	av::MediaFormat m_format;
	MediaPacketQueue	m_pktQueue;

    MediaTransportHeader	m_header;
    bool	m_headerReady;
    comn::ByteBuffer m_buffer;


};


} /* namespace av */

#endif /* TMEDIACASTERCONNECTION_H_ */
